package com.mairuide.one_click_search.controller;

import com.mairuide._frame.base.BaseController;
import com.mairuide.entity.PageResult;
import com.mairuide.entity.Result;
import com.mairuide.entity.StatusCode;
import com.mairuide.one_click_search.pojo.DataTemplate;
import com.mairuide.one_click_search.pojo.DataTemplateField;
import com.mairuide.one_click_search.service.DataTemplateFieldService;
import com.mairuide.one_click_search.service.DataTemplateService;
import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.response.FacetField;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description
 * @auther 刘中华
 * @create 2019-05-05 15:59
 */
@Controller
@RequestMapping("onekey_solr")
public class SolrController  extends BaseController {

    @RequestMapping(value = "/searchResultInit", method = RequestMethod.GET)
    public Object searchResultInit(ModelMap model,String keyword) {
        request.setAttribute("keyword",keyword);
        request.setAttribute("username",super.getLoginUser().getNickName());
        return "/one_click_search/searchResult";
    }
    @RequestMapping(value = "/oneIndexInit", method = RequestMethod.GET)
    public Object oneIndexInit(ModelMap model) {
        return "/one_click_search/oneIndex";
    }

    @Autowired
    private SolrClient solrClient;
    @Autowired
    DataTemplateService dataTemplateService;
    @Autowired
    DataTemplateFieldService dataTemplateFieldService;
    @Value("${solrCollection}")
    private String solrCollection;
    /**
     * @Author 刘中华
     * @Date 2019/5/5 16:01
     * @Param [keyword]
     * @return void
     * @Description 通过关键字来搜索左侧的树
     **/
    @RequestMapping("/facet")
    @ResponseBody
    public Result groupByTree(String keyword) throws Exception{
        ArrayList<Map<String,Object>> result = new ArrayList<>();
        /** 查出模板名字和模板code的对应关系 **/
        List<DataTemplate> templateList = dataTemplateService.findAll();
        Map<String, String> tableMap = templateList.stream().collect(Collectors.toMap(DataTemplate::getTablename, DataTemplate::getMobanname));
        /** 从solr中查询树的数据 **/
        SolrQuery query = new SolrQuery();//建立一个新的查询
        query.setQuery("\""+keyword+"\"");
        // 设置默认搜素域
        query.set("df", "onekey_keywords");
        query.setFacet(true);//设置facet=on
        query.addFacetField(new String[] { "tablename"});//设置需要facet的字段
        query.setFacetLimit(Integer.MAX_VALUE);//限制facet返回的数量
        QueryResponse response = solrClient.query(solrCollection,query);
        List<FacetField> facets = response.getFacetFields();//返回的facet列表
        for (FacetField facet : facets) {
            List<FacetField.Count> counts = facet.getValues();
            for (FacetField.Count count : counts) {
                if (count.getCount()>0){
                    HashMap<String,Object> map = new HashMap<>();
                    map.put("tablename",count.getName());
                    map.put("label",tableMap.get(count.getName())+" ("+count.getCount()+")");
                    result.add(map);
                }
            }
        }
        return new Result(true, StatusCode.OK,"操作成功",result);
    }

    @RequestMapping("/findData/{page}/{pageSize}")
    @ResponseBody
    public Result findListData(String keyword, String tablename, @PathVariable Integer page , @PathVariable Integer pageSize) throws Exception{
        ArrayList<Map<String, Object>> r = new ArrayList<>();
        if (StringUtils.isBlank(keyword)||StringUtils.isBlank(tablename)){
            return new Result(false, StatusCode.ERROR,"参数不能为空",r);
        }
        Map<String, DataTemplateField> colToFieldMap = dataTemplateFieldService.getColToFieldMap(tablename);
        SolrQuery query = new SolrQuery();
        query.set("q", "onekey_keywords:\""+keyword+"\" && tablename:\""+tablename+"\"");
        query.setStart((page-1)*pageSize);
        query.setRows(pageSize);
        query.setHighlight(true); // 开启高亮
        query.addHighlightField("F01,F02,F03,F04,F05,F06,F07,F08,F09,F10,F11,F12,F13,F14,F15,F16,F17,F18,F19,F20,F21,F22,F23,F24,F25,F26,F27,F28,F29,F30,F31,F32,F33,F34,F35,F36,F37,F38,F39,F40"); // 高亮字段
        query.setHighlightSimplePre("<span style='color:red'>"); // 高亮单词的前缀
        query.setHighlightSimplePost("</span>"); // 高亮单词的后缀
        QueryResponse response = solrClient.query(solrCollection, query);
        // 获取查询结果
        SolrDocumentList results = response.getResults();
        //获取高亮显示数据
        Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
        for (int i = 0; i < results.size(); i++) {
            SolrDocument document = results.get(i);
            String vid = (String) document.get("vid");
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("序号",i+1);
            map.put("vid",vid);
           //把solr的文档 的F01-F40  转换成 中文
            for (Map.Entry<String, DataTemplateField> entry : colToFieldMap.entrySet()) {
                DataTemplateField dataTemplateField = colToFieldMap.get(entry.getKey());
                if (dataTemplateField!=null){
                    Map<String, List<String>> listMap = highlighting.get(vid);
                    if(listMap.containsKey(dataTemplateField.getColname())){
                        map.put(dataTemplateField.getFiledname(), StringUtils.join(listMap.get(dataTemplateField.getColname()),""));
                    }else{
                        map.put(dataTemplateField.getFiledname(),document.get(dataTemplateField.getColname()));
                    }
                }
            }
            r.add(map);
        }
        long numFound = results.getNumFound();
        PageResult pageResult = new PageResult<>(numFound,r);
        return new Result(true, StatusCode.OK,"操作成功",pageResult);
    }
}
